package ar.com.jwa.jobs;

import java.util.Collection;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.transaction.annotation.Transactional;

import ar.com.jwa.domain.Game;
import ar.com.jwa.domain.State;
import ar.com.jwa.domain.User;
import ar.com.jwa.domain.emailing.Mail;
import ar.com.jwa.services.GameLocalService;
import ar.com.jwa.services.UserLocalService;


public class EmailingJob {

	private GameLocalService gameLocalService;
	
	private UserLocalService userLocalService;
	
	private Map<String,String> emailingConfiguration;
	
	private Mail dailyMail;
	
	private Log log = LogFactory.getLog(EmailingJob.class);
	
	@Transactional
	public void doEmailing(){
		
		if (mailEnabled()){
		
				this.log.info("Searching unplayed Games");
				
				Collection<Game> games = this.gameLocalService.getGamesByState(State.TO_CONFIRM);
				
				for (Game game : games) {
					
					Collection<User> confirmedPlayers = game.getConfirmedPlayers();
					
					for (User user : confirmedPlayers) {
						
						this.log.info("Sending Email to " + user.getNickName());
						
						this.getDailyMail().setTo(user);
						
						try {
							this.getDailyMail().send();
						} catch (Exception e) {
							log.error("Error happend trying to send emails: " + e.toString());
						}
					}
				}
			}
		}


	private boolean mailEnabled() {
		return Boolean.valueOf(emailingConfiguration.get("enabled"));
	}


	/**
	 * @return the gameLocalService
	 */
	public GameLocalService getGameLocalService() {
		return gameLocalService;
	}


	/**
	 * @param gameLocalService the gameLocalService to set
	 */
	public void setGameLocalService(GameLocalService gameLocalService) {
		this.gameLocalService = gameLocalService;
	}


	/**
	 * @return the userLocalService
	 */
	public UserLocalService getUserLocalService() {
		return userLocalService;
	}


	/**
	 * @param userLocalService the userLocalService to set
	 */
	public void setUserLocalService(UserLocalService userLocalService) {
		this.userLocalService = userLocalService;
	}


	/**
	 * @return the smtpServerConfiguration
	 */
	public Map<String, String> getEmailingConfiguration() {
		return emailingConfiguration;
	}


	/**
	 * @param smtpServerConfiguration the smtpServerConfiguration to set
	 */
	public void setEmailingConfiguration(
			Map<String, String> emailingConfiguration) {
		this.emailingConfiguration = emailingConfiguration;
	}


	/**
	 * @return the dailyMail
	 */
	public Mail getDailyMail() {
		return dailyMail;
	}


	/**
	 * @param dailyMail the dailyMail to set
	 */
	public void setDailyMail(Mail dailyMail) {
		this.dailyMail = dailyMail;
	}
}
